package com.soft.idc.common.control;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.ICallback;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.soft.idc.common.model.IdcAirplane;
import com.soft.idc.common.model.IdcDevice;
import com.soft.idc.common.model.IdcDeviceType;
import com.soft.idc.common.model.IdcOrg;
import com.soft.idc.common.model.IdcUser;
import com.soft.idc.common.service.IdcDeviceTypeService;
import com.soft.idc.common.service.IdcOrgService;
import com.soft.idc.common.util.JQPage;

public class DeviceManagerController extends Controller {
	public void index() {
		this.render("/device_manager/device_manager/device.html");
	}
	
	public void queryDevice() {
		int start = this.getParaToInt("start");
		int length = this.getParaToInt("length");
		IdcUser u = this.getSessionAttr("SYS_USER");
		StringBuffer sb = new StringBuffer();
		String code = this.getPara("code");
		String name = this.getPara("name");
		String type_id = this.getPara("type_id");
		String is_use = this.getPara("is_use");
		String plane_id = this.getPara("plane_id");
		String org_id = this.getPara("org_id");
		String orgIds = IdcOrgService.querySubOrgId(u.getOrgId());
		String tree_org_id = this.getPara("tree_org_id");
		String tree_type_id = this.getPara("tree_type_id");
		String tree_device_id = this.getPara("tree_device_id");
		String tree_plane_id = this.getPara("tree_plane_id");
		
		sb.append("select d.device_id, d.code, dt.name as type_name, d.modify_time, ");
		sb.append("d.is_use , o.name as org_name, d2.name as parent_name,  ");
		sb.append("p.name as plane_name, d.name , d.type_id, d.org_id, ");
		sb.append("d.parent_id, d.plane_id ");
		StringBuffer sqlFrom = new StringBuffer();
		
		sqlFrom.append("from idc_device d ");
		sqlFrom.append("left join idc_org o on d.org_id = o.org_id ");
		sqlFrom.append("left join idc_device_type dt on d.type_id = dt.type_id ");
		sqlFrom.append("left join idc_device d2 on d.parent_id = d2.device_id ");
		sqlFrom.append("left join idc_airplane p on d.plane_id = p.plane_id ");
		sqlFrom.append("where 1=1");
		
		if(orgIds.length()>0){
			sqlFrom.append(" and d.org_id in (" + orgIds + ") ");
		}
		if(code !=null ){
			sqlFrom.append(" and d.code like '%" + code + "%' ");
		}
		
		if(name !=null ){
			sqlFrom.append(" and d.name like '%" + name + "%' ");
		}
		
		if(type_id !=null ){
			sqlFrom.append(" and d.type_id = " + type_id);
		}
		
		if(is_use !=null ){
			sqlFrom.append(" and d.is_use = " + is_use);
		}
		if(plane_id !=null ){
			sqlFrom.append(" and d.plane_id = " + plane_id);
		}
		
		if(org_id !=null ){
			sqlFrom.append(" and d.org_id = " + org_id);
		}
		
		if(tree_plane_id != null){
			sqlFrom.append(" and d.plane_id = " + tree_plane_id);
		}
		
		if(tree_device_id != null){
			sqlFrom.append(" and d.device_id = " + tree_device_id);
		}
		
		if(tree_type_id != null){
			String typeIds = IdcDeviceTypeService.querySubTypeId(Integer.parseInt(tree_type_id));
			sqlFrom.append(" and d.type_id in (" + typeIds + ")");
		}
		if(tree_org_id !=null){
			String treeOrgIds = IdcOrgService.querySubOrgId(Integer.parseInt(tree_org_id));
			sqlFrom.append(" and d.org_id in (" + treeOrgIds + ") ");
		}
		int pageNum = start/length+1;
		
		Page<Record> page = Db.paginate(pageNum, length, sb.toString(), sqlFrom.toString());
		JQPage jPage = new JQPage(page);
		System.out.println(JsonKit.toJson(jPage));
		this.renderJson(jPage);
	}
	
	public void add() {
		IdcDevice device = new IdcDevice();
		String type_id = this.getPara("type_id");
		String parent_id = this.getPara("parent_id");
		String name = this.getPara("name");
		String code = this.getPara("code");
		String is_use = this.getPara("is_use");
		String is_air = this.getPara("is_air");
		String org_id = this.getPara("org_id");
		String plane_id = this.getPara("plane_id");
		Date now = new Date();
		IdcUser u = this.getSessionAttr("SYS_USER");
		if(type_id.length()>0){
			device.setTypeId(Integer.parseInt(type_id));
		}
		if(parent_id.length()>0){
			device.setParentId(Integer.parseInt(parent_id));
		}
		if(name.length()>0){
			device.setName(name);
		}
		if(code.length()>0){
			device.setCode(code);
		}
		if(is_use.length()>0){
			device.setIsUse(Integer.parseInt(is_use));
		}
		if(is_air.length()>0){
			device.setIsAir(Integer.parseInt(is_air));
		}
		if(org_id.length()>0){
			device.setOrgId(Integer.parseInt(org_id));
		}
		if(plane_id.length()>0){
			device.setPlaneId(Integer.parseInt(plane_id));
		}
		device.setCreateTime(now);
		device.setCreateUserId(u.getUserId());
		device.save();
//		String sql = "insert into idc_device (type_id, parent_id, name, code, is_use, "
//				+ "is_air, org_id, create_time, create_user_id, plane_id) values(?,?,?,?,?,?,?,?,?,?)";
//		int  result = Db.update(sql, new Object[]{type_id, parent_id, name, code, is_use, is_air, 
//				org_id, now , u.getUserId(),plane_id});
//		this.renderJson(result);
		this.renderJson(true);
	}
	
	public void delete() {
		final String deviceIds = this.getPara("deviceIds");
		ICallback call =new ICallback() {
			@Override
			public Object call(Connection conn) throws SQLException {
				// TODO Auto-generated method stub
				conn.setAutoCommit(false);
				String[] deviceIdsArr = deviceIds.split(";");
				StringBuffer sb = new StringBuffer();
				sb.append("delete from idc_device where device_id in(");
				for(int i=0; i<deviceIdsArr.length; i++){
					if(i==deviceIdsArr.length-1){
						sb.append(deviceIdsArr[i] + ")");
					}else{
						sb.append(deviceIdsArr[i] + ",");
					}
				}
				Statement sta = conn.createStatement();
				int count=sta.executeUpdate(sb.toString());
				if(count==deviceIdsArr.length){
					conn.commit();
					conn.close();
					return true;
				}else{
					conn.rollback();
					conn.close();
					return false;
				}
			}
		};
		Object obj = Db.execute(call);
		this.renderJson(obj);
	}
	
	public void edit() {
		IdcDevice device = new IdcDevice();
		String device_id = this.getPara("device_id");
		String type_id = this.getPara("type_id");
		String parent_id = this.getPara("parent_id");
		String name = this.getPara("name");
		String code = this.getPara("code");
		String is_use = this.getPara("is_use");
		String is_air = this.getPara("is_air");
		String org_id = this.getPara("org_id");
		String plane_id = this.getPara("plane_id");
		Date now = new Date();
		IdcUser u = this.getSessionAttr("SYS_USER");
		device.setDeviceId(Integer.parseInt(device_id));
		if(type_id.length()>0){
			device.setTypeId(Integer.parseInt(type_id));
		}
		if(parent_id.length()>0){
			device.setParentId(Integer.parseInt(parent_id));
		}
		if(name.length()>0){
			device.setName(name);
		}
		if(code.length()>0){
			device.setCode(code);
		}
		if(is_use.length()>0){
			device.setIsUse(Integer.parseInt(is_use));
		}
		if(is_air.length()>0){
			device.setIsAir(Integer.parseInt(is_air));
		}
		if(org_id.length()>0){
			device.setOrgId(Integer.parseInt(org_id));
		}
		if(plane_id.length()>0){
			device.setPlaneId(Integer.parseInt(plane_id));
		}
		device.setModifyTime(now);
		device.setModifyUserId(u.getUserId());
		boolean result= device.update();
//		String sql = "update idc_device set type_id=?, parent_id=?, name=?, code=?, is_use=?, "
//				+ "is_air=?, org_id=?, modify_time=?, modify_user_id=?, plane_id=? where device_id = ? ";
//		int  result = Db.update(sql, new Object[]{type_id, parent_id, name, code, is_use, is_air, 
//				org_id, now , u.getUserId(),plane_id,device_id});
//		this.renderJson(result);
		this.renderJson(result);
	}
	
	public void getDeviceTypeList(){
		StringBuffer sb = new StringBuffer();
		sb.append("select type_id, name from idc_device_type ");
		List<Record>  result = Db.find(sb.toString());
		this.renderJson(result);
	}
	
	public void getOrgList(){
		IdcUser u = this.getSessionAttr("SYS_USER");
		List<Record> result = IdcOrgService.querySubOrg(u.getOrgId());
		this.renderJson(result);
	}
	
	public void getDeviceList(){
		IdcUser u = this.getSessionAttr("SYS_USER");
		List<Record> result = IdcOrgService.querySubOrg(u.getOrgId());
		StringBuffer orgIds = new StringBuffer();
		for(int i=0; i<result.size(); i++){
			if(i!=result.size()-1){
				orgIds.append(result.get(i).getInt("org_id") + ",");
			}else{
				orgIds.append(result.get(i).getInt("org_id"));
			}
		}
		StringBuffer sql = new StringBuffer();
		sql.append("select  d.device_id, d.name from idc_device d ");
		if(orgIds.length()>0){
			sql.append("where d.org_id in (" + orgIds.toString() + ")");
		}
		List<Record>  rt = Db.find(sql.toString());
		this.renderJson(rt);
	}
	
	public void getPlaneList(){
		IdcUser u = this.getSessionAttr("SYS_USER");
		String orgIds = IdcOrgService.querySubOrgId(u.getOrgId());
		StringBuffer sql = new StringBuffer();
		sql.append("select  a.plane_id, a.name from idc_airplane a ");
		if(orgIds.length()>0){
			sql.append("where a.org_id in (" + orgIds + ")");
		}
		List<Record>  rt = Db.find(sql.toString());
		this.renderJson(rt);
	}
	
	public void getTreeData(){
		IdcUser u = this.getSessionAttr("SYS_USER");
		String id = this.getPara("id");
		String name = this.getPara("name");
		List result = new ArrayList();
		//首次加载树
		if(id==null||name==null){
			IdcOrg org = new IdcOrg();
			org = org.findById(u.getOrgId());
			if(org.getParentId()==-1){
				List<IdcOrg> orgList = org.find("select * from idc_org where parent_id = ? ",
						new Object[]{org.getOrgId()});
				//遍历一级节点--组织
				for(IdcOrg orgElement:orgList){
					Map orgNodeMap = new HashMap();
					orgNodeMap.put("id", orgElement.getOrgId() + "_org");
					orgNodeMap.put("pid", "0");
					orgNodeMap.put("name", orgElement.getName());
					orgNodeMap.put("isParent", true);
					result.add(orgNodeMap);
				}
			}else{
				Map orgNodeMap = new HashMap();
				orgNodeMap.put("id", org.getOrgId() + "_org");
				orgNodeMap.put("pid", "0");
				orgNodeMap.put("name", org.getName());
				orgNodeMap.put("isParent", true);
				result.add(orgNodeMap);
			}
		}else{
			if(id.contains("org")){
				String orgId = id.substring(0, id.indexOf("_org"));
				IdcOrg idcOrg = new IdcOrg();
				idcOrg = idcOrg.findById(orgId);
				if(idcOrg.getOrgType()==1){
					//地面设备
					IdcDeviceType idcDeviceType = new IdcDeviceType();
					List<IdcDeviceType> idcDeviceTypeList = idcDeviceType.find("select * from idc_device_Type t where t.is_air = 0 order by type_id asc");
					//查出所有属于地面设备组织的设备
//					String orgIds = IdcOrgService.querySubOrgId(idcOrg.getOrgId());
//					 List<IdcDevice> deviceList = idcDevice.find("select * from idc_device d where d.org_id in (" + orgIds + ")");
					 if(idcDeviceTypeList.size()>0){
//						 StringBuffer sb = new StringBuffer();
//						 //查出所有设备类型ID
//						 for(int i=0; i<deviceList.size(); i++){
//							 if(i!=deviceList.size()-1){
//								 sb.append(deviceList.get(i).getTypeId() + ",");
//							 }else{
//								 sb.append(deviceList.get(i).getTypeId());
//							 }
//						 }
//						 String typeResult = Db.queryStr("SELECT queryParentByTypeIds(?) as result" , new Object[]{sb.toString()});
//						 typeResult = typeResult.replace("$", sb.toString());
//						 //查出所有设备类型实体
//						 IdcDeviceType idcDeviceType = new IdcDeviceType();
//						 List<IdcDeviceType> idcDeviceTypeList =idcDeviceType
//								 	.find("select * from idc_device_type t where t.type_id in (" 
//								 	+ typeResult + ") order by type_id asc" );
						 for(int i=0; i<idcDeviceTypeList.size(); i++){
							 Map deviceTypeMap = new HashMap();
							 idcDeviceType = idcDeviceTypeList.get(i);
							 if(idcDeviceType.getParentId()==-1){
								 deviceTypeMap.put("id", idcDeviceType.getTypeId() + "_type");
								 deviceTypeMap.put("pid", id);
								 deviceTypeMap.put("name", idcDeviceType.getName());
								 deviceTypeMap.put("isParent", true);
								 deviceTypeMap.put("open", true);
							 }else{
								 deviceTypeMap.put("id", idcDeviceType.getTypeId() + "_type");
								 deviceTypeMap.put("pid", idcDeviceType.getParentId() + "_type");
								 deviceTypeMap.put("name", idcDeviceType.getName());
								 deviceTypeMap.put("open", true);
							 }
							 result.add(deviceTypeMap);
						 }
					 }
				}else{
					//非地面设备
					IdcAirplane idcAirplane = new IdcAirplane();
					String orgIds = IdcOrgService.querySubOrgId(idcOrg.getOrgId());
					//查出该组织下的所有飞机
					List<IdcAirplane> idcAirplaneList = idcAirplane
							.find("select * from idc_airplane p where p.org_id in (" + orgIds + ") order by plane_id asc");
					for(int i=0; i<idcAirplaneList.size(); i++){
						Map planeMap = new HashMap();
						idcAirplane = idcAirplaneList.get(i);
						planeMap.put("id", idcAirplane.getPlaneId() + "_plane");
						planeMap.put("pid", id);
						planeMap.put("name", idcAirplane.getCode());
						planeMap.put("isParent", true);
						result.add(planeMap);
					}
				}
				
			}else if(id.contains("plane")){
				IdcDeviceType idcDeviceType = new IdcDeviceType();
				List<IdcDeviceType> idcDeviceTypeList = idcDeviceType.find("select * from idc_device_Type t where t.is_air = 1 order by type_id asc");
				
//				
//				IdcDevice idcDevice = new IdcDevice();
//				List<IdcDevice> idcDeviceList =idcDevice.find("select * from idc_device d where d.plane_id = " 
//									+ id.substring(0, id.indexOf("_plane")));
				if(idcDeviceTypeList.size()>0){
//					 StringBuffer sb = new StringBuffer();
//					 //查出所有设备类型ID
//					 for(int i=0; i<idcDeviceList.size(); i++){
//						 if(i!=idcDeviceList.size()-1){
//							 sb.append(idcDeviceList.get(i).getTypeId() + ",");
//						 }else{
//							 sb.append(idcDeviceList.get(i).getTypeId());
//						 }
//					 }
//					 String typeResult = Db.queryStr("SELECT queryParentByTypeIds(?) as result" , new Object[]{sb.toString()});
//					 typeResult = typeResult.replace("$", sb.toString());
//					 IdcDeviceType idcDeviceType = new IdcDeviceType();
//					 List<IdcDeviceType> idcDeviceTypeList =idcDeviceType
//							 	.find("select * from idc_device_type t where t.type_id in (" 
//							 	+ typeResult + ") order by type_id asc" );
					 for(int i=0; i<idcDeviceTypeList.size(); i++){
						 Map deviceTypeMap = new HashMap();
						 idcDeviceType = idcDeviceTypeList.get(i);
						 if(idcDeviceType.getParentId()==-1){
							 deviceTypeMap.put("id", idcDeviceType.getTypeId() + "_type");
							 deviceTypeMap.put("pid", id);
							 deviceTypeMap.put("name", idcDeviceType.getName());
							 deviceTypeMap.put("isParent", true);
							 deviceTypeMap.put("open", true);
						 }else{
							 deviceTypeMap.put("id", idcDeviceType.getTypeId() + "_type");
							 deviceTypeMap.put("pid", idcDeviceType.getParentId() + "_type");
							 deviceTypeMap.put("name", idcDeviceType.getName());
							 deviceTypeMap.put("open", true);
						 }
						 result.add(deviceTypeMap);
					 }
				}
			}
		}
		
		this.renderJson(result);
	}
}
